package com.example.aigc_education.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.constant.CacheConstants;
import com.example.aigc_education.domain.Todo;
import com.example.aigc_education.domain.dto.SubTodoDTO;
import com.example.aigc_education.domain.dto.TodoDTO;
import com.example.aigc_education.service.TodoService;
import com.example.aigc_education.utils.RedisCache;
import com.example.aigc_education.utils.ResultUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@RequestMapping("/todo")
@RestController
public class TodoController {

    // 颜色列表
    private static final List<String> COLORS = Arrays.asList("#3665a6", "#5389b7", "#069aa2", "#a36484", "#5c9572", "#c18d6c");
    // 随机数生成器
    private static final Random RANDOM = new Random();

    @Resource
    private TodoService todoService;

    @Resource
    private RedisCache redisCache;

    /**
     * 获取某些计划的待办事项
     * @param planId 计划id
     * @return 返回当前计划的待办事项
     */
    @GetMapping("/all/{planId}")
    public ResultUtil getAllTodos(@PathVariable Long planId) {
        List<Todo> todoList = todoService.list(new LambdaQueryWrapper<Todo>().eq(Todo::getPlanId, planId));
        return ResultUtil.success(todoList);
    }

    /**
     * 获取某项计划中特定章节的待办事项
     * @param planId 计划id
     * @param chapter 章节
     * @return 返回待办事项
     */
    @GetMapping("/byChapter/{planId}/{chapter}")
    public ResultUtil getTodoByChapter(@PathVariable Long planId,
                                       @PathVariable String chapter) {
        List<Todo> todoList = todoService.list(new LambdaQueryWrapper<Todo>().eq(Todo::getPlanId, planId).eq(Todo::getChapter, chapter));
        return ResultUtil.success(todoList);
    }

    /**
     * 更新待办事项完成情况（subTodo传入版）
     * 未包装成Service层的方法（待处理）
     * @param planId 计划id
     * @param todoDTO 子待办事项完成情况（JSON格式）
     * @return 返回更新结果
     */
    @PutMapping("/update")
    public ResultUtil updateTodo(Long planId, TodoDTO todoDTO) {
        List<Todo> todoList = todoService.list(new LambdaQueryWrapper<Todo>().eq(Todo::getPlanId, planId));
        todoList.forEach(todo -> {
            if (todoDTO.getTodoTitle().equals(todo.getTodoTitle())){
                String jsonString = JSON.toJSONString(todoDTO.getSubTodos());
                todo.setSubTodos(jsonString);
                List<SubTodoDTO> subTodos = todoDTO.getSubTodos();
                int count = 0;
                for (SubTodoDTO subTodo : subTodos) {
                    if (subTodo.getIsComplete() == 1) count++;
                }
                if (count == subTodos.size()) {
                    todo.setIsComplete(1);
                    long chapterRes = todoService.count(new LambdaQueryWrapper<Todo>().eq(Todo::getPlanId, planId).eq(Todo::getChapter, todo.getChapter()));
                    long isCompleteChapter = todoService.count(new LambdaQueryWrapper<Todo>().eq(Todo::getPlanId, planId).eq(Todo::getChapter, todo.getChapter()).eq(Todo::getIsComplete, 1));
                    if (chapterRes == isCompleteChapter) {
                        // 可插入颜色背景作为标志，用redis持久化,以章节划分区域
                        String color = getRandomColor();
                        redisCache.setCacheObject(CacheConstants.TODO_COMPLETE_KEY + todo.getPlanId()+ ":" + todo.getChapter(), color);
                    }
                }
                boolean saved = todoService.updateById(todo);
                if (!saved) throw new BusinessException("更新失败");
            }
        });
        return ResultUtil.success("更新成功");
    }


    /**
     * 获取某项计划中所执行的某个章节的待办事项
     * 点击某个计划，直接出现当前未完成章节的待办事项，
     * 已完成的章节可以通过点击某些章节去展示已完成事项，
     * 未完成的需要只有当前章节完成后才会展示

     * 视图层subTodos仍然是字符串未JSON格式化
     * @param planId 计划id
     * @return 返回待办事项
     */
    @GetMapping("/currentChapter/{planId}")
    public ResultUtil getTodoByCurrentChapter(@PathVariable Long planId) {
        List<Todo> currentTodoList = todoService.list(new LambdaQueryWrapper<Todo>().eq(Todo::getPlanId, planId).eq(Todo::getIsCurrentChapter, 1));
        if (currentTodoList.size() == 0) {
            return ResultUtil.success("当前计划已完成");
        }
        // List<Todo> --> List<TodoDTO>
        List<TodoDTO> todoDTOList = currentTodoList.stream().map(todo -> {
            TodoDTO todoDTO = new TodoDTO();
            todoDTO.setTodoTitle(todo.getTodoTitle());
            List<SubTodoDTO> subTodoDTOS = JSON.parseArray(todo.getSubTodos(), SubTodoDTO.class);
            todoDTO.setSubTodos(subTodoDTOS);
            todoDTO.setSuggestTime(todo.getSuggestTime());
            todoDTO.setChapter(todo.getChapter());
            todoDTO.setKnowledgePointer(todo.getKnowledgepointer());
            todoDTO.setIsComplete(todo.getIsComplete());
            todoDTO.setType(todo.getType());
            return todoDTO;
        }).collect(Collectors.toList());

        // 当前计划下的任务全部完成，则不会再去更新到下一章节（已经没有下一个章节）
        return ResultUtil.success(todoDTOList);
    }

    // 随机颜色生成器
    private String getRandomColor() {
        int index = RANDOM.nextInt(COLORS.size());
        return COLORS.get(index);
    }
}
